import { Empty, Modal, Skeleton } from 'antd'
import Image from 'next/image'
import { useEffect, useState } from 'react'
import React from 'react'

import { Violation } from '@/api/interface'
import { ReplyRes } from '@/api/interface/entity'
import { ReplyList } from '@/api/modules/entity'
import file from '@/assets/images/file.png'
import left from '@/assets/images/left.png'
import useLocale from '@/utils/useLocale'

import locale from './locale'
import styles from './styles/replied.module.less'

function Replied({
  violation,
  isModalOpen,
  setIsModalOpen,
}: {
  violation: Partial<Violation>
  isModalOpen: boolean
  setIsModalOpen: (_: boolean) => void
}) {
  const t = useLocale(locale)

  useEffect(() => {
    isModalOpen && getRepliedList()
  }, [isModalOpen])

  const [loading, setLoading] = useState(true)
  const [replied, setReplied] = useState<ReplyRes[][]>([])
  const getRepliedList = async () => {
    try {
      setLoading(true)
      const { data } = await ReplyList({ refNumber: violation.refNumber! })
      const filteredData = []
      if (data.length === 1) {
        filteredData.push(data)
      } else {
        for (let i = 0; i < data.length; i++) {
          const obj = data[i]
          const matchingObj = data.find((item) => item.id === obj.replyTo)
          if (matchingObj) {
            const index = filteredData.findIndex((arr) =>
              arr.some((el) => el.id === matchingObj.id)
            )
            if (index !== -1) filteredData[index].push(obj)
            else filteredData.push([matchingObj, obj])
          }
        }
      }
      setReplied(filteredData)
    } finally {
      setLoading(false)
    }
  }

  const handleCancel = () => {
    setIsModalOpen(false)
  }

  const Title = () => {
    return (
      <div className={styles['replied-header-title']}>
        <Image
          src={left}
          alt="left"
          className={styles['title-icon']}
          onClick={() => handleCancel()}
        />
        <span className={styles['title-text']}>{t['reply.title.replied']}</span>
      </div>
    )
  }

  return (
    <Modal
      centered
      width={900}
      title={<Title />}
      footer={false}
      open={isModalOpen}
      onCancel={handleCancel}
      className={styles['replied-modal']}
      classNames={{
        header: styles['replied-header'],
        body: styles['replied-body'],
      }}
      wrapClassName={styles['replied-wrapper']}
    >
      <Skeleton
        loading={loading}
        title={false}
        active
        paragraph={{ rows: 15 }}
        style={{ padding: '20px' }}
      >
        <div className={styles['replied']}>
          {replied.length ? (
            <div className={styles['replied-list']}>
              {replied.map((item, index) => {
                return (
                  <div className={styles['replied-item']} key={index}>
                    <div className={styles['replied-header']} />
                    <div className={styles['replied-main']}>
                      <div className={styles['replied-comment']}>
                        {item.map((subItem, subIndex) => {
                          return (
                            <div className={styles['replied-comment-item']} key={subIndex}>
                              <span className={styles['comment-title']}>
                                {`${subItem.createdBy} ${
                                  subItem.source === 'INT' ? 'commented :' : 'replied :'
                                } `}
                              </span>
                              <span className={styles['comment-text']}>
                                {subItem.content ? subItem.content : '--'}
                              </span>
                              {subItem.attachment?.length ? (
                                <div className={styles['replied-file']}>
                                  {subItem.attachment?.map((item) => {
                                    return (
                                      <div className={styles['replied-file-item']} key={item}>
                                        <Image
                                          src={file}
                                          className={styles['file-icon']}
                                          alt="file"
                                        />
                                        <span className={styles['file-text']}>{item}</span>
                                      </div>
                                    )
                                  })}
                                </div>
                              ) : (
                                <></>
                              )}
                            </div>
                          )
                        })}
                      </div>
                    </div>
                  </div>
                )
              })}
            </div>
          ) : (
            <Empty description={false} style={{ padding: '100px 0 150px' }} />
          )}
        </div>
      </Skeleton>
    </Modal>
  )
}
export default Replied
